<?php

namespace App\Models\CacheModel\zlcr3;

use App\Models\CacheModel\ZlcrAstr;
use App\Models\Api\BaseCache;
use traits\model\SoftDelete;
use AstroTool\Cache\CacheManage;

class Zlcr3ConsultChatRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr3_consult_chat_record';

    protected $cacheModel = 'voice_consult.chat_id';

    use SoftDelete;

    /**
     * 初始化 咨询会话ID
     * @param array $data
     * @return int
     */
    public function SaveData(array $data): int
    {
        try
        {
            $chatId = $this->insertGetId($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('astrid_chat_id', $data['uid'] . ':' . $data['astr_id'])->rmCache('astrid_chat_id');

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['uid'])->rmCache('list');
            return (int)$chatId;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    public function updateData($chatId, $data)
    {
        try
        {
            $data['update_time'] = time();
            $this->where(['id' => $chatId])->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $chatId)->rmCache();
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {   // 获取未删除 的数据
            $where = ['id' => ['in', $ids]];
        } else
        {   // 获取指定pid  未删除 且 未隐藏的数据
            $where = ['uid' => $type[0]];
        }
        $field = 'uid,astr_id,last_chat_detail_id,last_chat_detail_time,msg_num,create_time,update_time';
        try
        {
            $data = $this
                ->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'astr_id', 'uid', 'msg_num', 'last_chat_detail_id', 'last_chat_detail_time', 'create_time', 'update_time']);
        }

        return $data;
    }

    /**
     * 对话记录删除
     * @param int $uid
     * @param int $astrId
     * @param int $chatId
     * @return bool
     * @throws \Exception
     */
    public function delChat(int $uid, int $astrId, int $chatId): bool
    {
        try
        {
            $this::destroy($chatId);
        }
        catch (\Exception $e)
        {
            return false;
        }

        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache('list');
        CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('astrid_chat_id', $uid . ':' . $astrId)->rmCache('astrid_chat_id');

        return true;
    }

    /**
     * 获取指定  咨询师的会话ID chatId
     * @param int $astrId
     * @return int
     * @throws \Exception
     */
    public function getChatIdByAstrId(int $uid, int $astrId): int
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('astrid_chat_id', $uid . ':' . $astrId)
            ->getDataAndSet(function () use ($uid, $astrId)
            {
                try
                {
                    $id = $this->where(['uid' => $uid])->where('astr_id', $astrId)->order('id desc')->value('id');
                    if ($id)
                    {
                        $data = ['id' => $id];
                    } else
                    {
                        $data = ['id' => 0];
                    }
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = ['id' => 0];
                }
                return $data;
            }, [], 'astrid_chat_id');

        return (int)($data['id'] ?? 0);
    }

    /**
     * 分页数据 重组
     * @param array $data
     * @return array
     * @throws \Exception
     */
    public function pageDataResert(array $data)
    {
        $resData = [];
        $now0Time = strtotime(date('Y-m-d')); // 今日0点时间
        $nowTime = time(); // 当前时间
        $consultChatRecordDetailsModel = new Zlcr3ConsultChatRecordDetails();
        foreach ($data as $key => $item)
        {
            $astrInfo = (new ZlcrAstr())->getInfoById($item['astr_id'], ['nickname', 'avatar']);

            $chatDetail = $consultChatRecordDetailsModel->getInfoById($item['last_chat_detail_id'], ['content', 'data_type', 'extend']);

            switch ($chatDetail['data_type'])
            {
                case 1:
                case 4:
                    $content = $chatDetail['content'];
                    break;
                case 2:
                    $content = '[图片]';
                    break;
                case 3:
                    $content = '[语音连线]';
                    break;
                case 5:
                    $content = '收到问题回复';
                    break;
                default:
            }

            $resData[] = [
                'id' => $item['astr_id'],
                'name' => $astrInfo['nickname'],
                'avatar' => $astrInfo['avatar'],
                'des' => $content ?? '',
                'des_color' => $item['msg_num'] > 0 ? '#FF5151' : '#9FA1AA',
                'msg_num' => $item['msg_num'],
                'time' => $this->timeConvert($item['last_chat_detail_time'], $now0Time, $nowTime),
            ];
        }

        return $resData;
    }

    /**
     * 时间转换
     * @param int $time 待转换的时间
     * @param int $now0Time 今日零点时间
     * @return string
     */
    public function timeConvert(int $time, int $now0Time, int $nowTime)
    {
        $t = $now0Time - $time;
        if ($t <= 0)
        {
            $t2 = $nowTime - $time;

            if ($t2 < 3600)
            {
                $i = floor($t2 / 60);
                $timeStr = max($i, 1) . '分钟前';
            } elseif ($t2 < 7200)
            {
                $timeStr = '1小时前';
            } else
            {
                $timeStr = date('H:i', $time);
            }
        } elseif ($t <= 86400)
        {
            $timeStr = date('昨日', $time);
        } else
        {
            $timeStr = date('m月d日', $time);
        }

        return $timeStr;
    }

    /**
     * 获取 用户咨询消息未读总数
     * @param int $uid
     * @return int
     * @throws \Exception
     */
    public function getUserUnreadAllNum(int $uid): int
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('unread_num', $uid)
            ->getDataAndSet(function () use ($uid)
            {
                try
                {
                    $dataList = $this->where(['uid' => $uid])->column('msg_num', 'id');

                    $data = [0 => 0];

                    foreach ($dataList as $id => $num)
                    {
                        $data[$id] = $num;
                    }

                    return $data;
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = [0 => 0];
                }
                return $data;
            }, [], 'unread_num');

        return (int)array_sum($data);
    }

    /**
     * 更新 用户咨询消息未读总数 增加
     * @param int $uid
     * @param int $chatId
     * @param int $type 类型 1=>自增未读数 2=>设置未读数
     * @param int $num 变更数量
     * @return void
     * @throws \Exception
     */
    public function setUserUnreadChatIdMsgNum(int $uid, int $chatId, int $type, int $num = 1)
    {
        if ($type === 1)
        {   // 自增未读 消息数量
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('unread_num', $uid)->setCacheInc($chatId, 'unread_num', $num);
        } else
        {   // 设置 未读消息 数量
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('unread_num', $uid)->setCache([$chatId => $num], 'unread_num', true);
        }
    }
}
